/* eslint-disable @typescript-eslint/no-unused-vars */
<template>
  <g-dialog
      :show-dialog="dialogDisplay"
      :title="title"
      @onSave="saveTag"
      @onCancel="closeDialog"
      ref="dialogRef"
      >
    <template v-slot:default>

      <q-form ref="tagForm">
        <q-select
            outlined
            v-model="selectedOption"
            :options="options"
            label="标签前缀"
            option-value="id"
            option-label="name"
            :disable="editMode"
            style="padding-bottom: 20px;" />

        <q-input
            outlined
            v-model="tagInfo.tagName"
            label="标签名称"
            lazy-rules
            :rules="[ (val: String) => validateTagName(val) || '30个字符以内且不能只有前缀名']"
            :disable="editMode"
        />

        <q-input
            outlined
            type="number"
            v-model="tagInfo.maxId"
            label="当前最大ID"
            lazy-rules
            :rules="[ (val: Number) => (val && val >= 0 || val === 0) || '当前最大ID必须大于等于0']"
            :disable="editMode"
        />


        <q-input
            outlined
            type="number"
            v-model="tagInfo.step"
            label="发号步长"
            lazy-rules
            :rules="[ (val: Number) => val && val > 0 || '发号步长必须大于0']"
        />

        <q-input
            outlined
            v-model="tagInfo.description"
            label="标签描述"
            lazy-rules
            :rules="[ (val: String) => val && val.length > 0 && val.length < 50 || '请输入50个字符以内的标签描述']"
        />
      </q-form>
    </template>
  </g-dialog>
</template>

<script lang="ts">
import GDialog from "../../../components/interaction/GDialog.vue";
import {QForm, QInput, QSelect, useDialogPluginComponent} from "quasar";
import {defineComponent, onMounted, PropType, ref, watch} from "vue";
import {Tag} from "../../../types/tag";
import {showError, showSuccess} from "../../../utils/notify";
import md5Hex from "md5-hex";
import {Prefix} from "../../../types/prefix";

export default defineComponent({
  name: "TagEdit",
  components: {
    GDialog,
    QForm,
    QInput,
    QSelect,
  },
  props: {
    title: {
      type: String,
      required: true
    },
    id: {
      type: Number,
      required: false,
      default: -1
    },
    init: {
      type: Object as PropType<Tag>,
      required: true
    },
    getById: {
      type: Function as PropType<(id: number) => Promise<Tag>>,
      required: true
    },
    add: {
      type: Function as PropType<(tag: Tag) => Promise<void>>,
      required: true
    },
    edit: {
      type: Function as PropType<(tag: Tag) => Promise<void>>,
      required: true
    },
    options: {
      type: Array as PropType<Prefix[]>,
      required: true
    }
  },
  emits: [],
  setup(props, context) {
    const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent()

    const dialogDisplay = ref<boolean>(true)

    // 表单引用
    const tagForm = ref(null)
    // 是否为编辑模式
    const editMode = ref<boolean>(props.id !== -1)
    // 标签信息 md5 值，编辑标签时如果字段没有变更则不调用后台接口
    let tagInfoHash = ''
    // 标签信息
    const tagInfo = ref<Tag>(props.init)

    // const selectedOption = ref<Prefix>({
    //   id: -1,
    //   name: '无前缀',
    //   description: '不使用前缀'
    // })

    const selectedOption = ref(null)

    watch(selectedOption, (newVal, oldVal) => {
      const oldNameParts: Array<string> = tagInfo.value.tagName.split('_')
      let pureName = oldNameParts[0]
      if (oldNameParts.length == 2) {
        pureName = oldNameParts[1]
      }
      // @ts-ignore
      if (newVal.id === -1) {
        tagInfo.value.tagName = pureName
      } else {
        // @ts-ignore
        tagInfo.value.tagName = newVal.name + "_" + pureName
      }
    })

    onMounted(() => {
      if (props.id !== -1) {
        props.getById(props.id).then(res => {
          tagInfo.value = res
          // @ts-ignore
          selectedOption.value = props.options.find(opt => opt.id === tagInfo.value.prefixId)
          tagInfoHash = md5Hex(JSON.stringify(tagInfo.value))
        }).catch(err => {
          closeDialog()
        })
      } else {
        // @ts-ignore
        selectedOption.value = {
          id: -1,
          name: '无前缀',
          description: '不使用前缀'
        }
      }
    })

    function saveTag() {
      // @ts-ignore
      tagForm.value.validate().then(success => {
        if (success) {
          // @ts-ignore
          tagInfo.value.prefixId = selectedOption.value.id
          if (editMode.value) {
            let editedHash = md5Hex(JSON.stringify(tagInfo.value))
            if (tagInfoHash === editedHash) {
              showSuccess('编辑标签成功')
              closeDialog()
              return
            }
            props.edit(tagInfo.value).then(res => {
              showSuccess('编辑标签成功')
              closeDialog()
            }).catch(err => {
              showError('编辑标签失败')
              closeDialog()
            })
          } else {
            props.add(tagInfo.value).then(res => {
              showSuccess('新增标签成功')
              closeDialog()
            }).catch(err => {
              showError('新增标签失败')
              closeDialog()
            })
          }
        }
      })
    }

    function closeDialog() {
      dialogDisplay.value = false
      return true
    }

    function validateTagName(tagName: String) {
      // @ts-ignore
      if (selectedOption.value.id !== -1) {
        // @ts-ignore
        return tagName && tagName.length > 0 && tagName.length < 30 && !tagName.trim().endsWith(selectedOption.value.name + '_')
      }
      return tagName && tagName.length > 0 && tagName.length < 30
    }

    return {
      selectedOption,
      editMode,
      dialogRef,
      dialogDisplay,
      tagForm,
      tagInfo,
      saveTag,
      closeDialog,
      validateTagName
    }
  }
})
</script>

<style scoped>

</style>